package com.bootdo.wx.api;

import com.alibaba.fastjson.JSONObject;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.common.utils.UuidUtil;
import com.bootdo.wx.domain.DeviceInfoDO;
import com.bootdo.wx.domain.TestDataDo;
import com.bootdo.wx.service.DataRangeService;
import com.bootdo.wx.service.DeviceInfoService;
import com.bootdo.wx.service.TestDataService;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 设备接口
 *
 * @autor LCL
 * @date 2020-09-12
 */

@RestController
@RequestMapping("/api/device")
public class ApiDeviceController {

    @Autowired
    private DeviceInfoService deviceInfoService;

    @Autowired
    private TestDataService testDataService;

    @Autowired
    private DataRangeService dataRangeService;

    /**
     * 上传设备信息
     *
     * device:设备编号
     * device_name:设备名称
     */
    @ResponseBody
    @PostMapping("/uploadDeviceList")
    public R uploadDeviceList(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("device") || StringUtils.isBlank(params.get("device").toString())
                || !params.containsKey("device_name") || StringUtils.isBlank(params.get("device_name").toString())

        ) {
            return R.error("参数异常");
        }
        try {
            String deviceId = params.get("device").toString();
            DeviceInfoDO deviceDO = deviceInfoService.getDeviceId(deviceId);
            //规定格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            //获取当前时间
            Date dateNow = new Date();
            if (deviceDO == null) {
                DeviceInfoDO infoDO = new DeviceInfoDO();
                infoDO.setId(UuidUtil.get32UUID());
                infoDO.setDevice(params.get("device").toString());
                infoDO.setDeviceName(params.get("device_name").toString());
                infoDO.setCreateAt(sdf.format(dateNow));
                infoDO.setStatus(0);
                infoDO.setDelFlag(0);
                deviceInfoService.save(infoDO);
            } else {
                DeviceInfoDO inDO = new DeviceInfoDO();
                //inDO.setId(UuidUtil.get32UUID());
                inDO.setDevice(params.get("device").toString());
                inDO.setDeviceName(params.get("device_name").toString());
                deviceInfoService.update(inDO);
            }
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
    }

    /**
     * 获取设备信息
     *
     * device:设备编号
     */
    @ResponseBody
    @PostMapping("/getDeviceList")
    public R getDeviceList(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("device") || StringUtils.isBlank(params.get("device").toString())) {
            return R.error("缺少参数");
        }
        try {
            List<DeviceInfoDO> List = deviceInfoService.getDeviceList(params);
            return R.ok().put("data", List);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取失败");
        }
    }

    /**
     * 上传检测参数
     *
     * device:设备编号
     * name:
     * value:
     * year:
     * month:
     * day:
     * hour:
     * minute:
     * lng_degree:
     * lng_minute:
     * lng_second:
     * lat_degree:
     * lat_minute:
     * lat_second:
     */
    @ResponseBody
    @PostMapping("/uploadTestList")
    public R uploadTestList(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("device") || StringUtils.isBlank(params.get("device").toString())
                || !params.containsKey("name") || StringUtils.isBlank(params.get("name").toString())
                || !params.containsKey("value") || StringUtils.isBlank(params.get("value").toString())
                || !params.containsKey("year") || StringUtils.isBlank(params.get("year").toString())
                || !params.containsKey("month") || StringUtils.isBlank(params.get("month").toString())
                || !params.containsKey("day") || StringUtils.isBlank(params.get("day").toString())
                || !params.containsKey("hour") || StringUtils.isBlank(params.get("hour").toString())
                || !params.containsKey("minute") || StringUtils.isBlank(params.get("minute").toString())
                || !params.containsKey("lng_degree") || StringUtils.isBlank(params.get("lng_degree").toString())
                || !params.containsKey("lng_minute") || StringUtils.isBlank(params.get("lng_minute").toString())
                || !params.containsKey("lng_second") || StringUtils.isBlank(params.get("lng_second").toString())
                || !params.containsKey("lat_degree") || StringUtils.isBlank(params.get("lat_degree").toString())
                || !params.containsKey("lat_minute") || StringUtils.isBlank(params.get("lat_minute").toString())
                || !params.containsKey("lat_second") || StringUtils.isBlank(params.get("lat_second").toString())
        ) {
            return R.error("缺少参数");
        }
        try {
            TestDataDo dataDo = new TestDataDo();
            dataDo.setId(UuidUtil.get32UUID());
            dataDo.setDevice(params.get("device").toString());
            dataDo.setName(params.get("name").toString());
            dataDo.setValue(params.get("value").toString());
            dataDo.setYear(params.get("year").toString());

            String month = params.get("month").toString();
            String day = params.get("day").toString();
            String hour = params.get("hour").toString();
            String minute = params.get("minute").toString();

            if (isnumberic(month)==1) {
                dataDo.setMonth("0"+month);
            } else {
                dataDo.setMonth(params.get("month").toString());
            }
            if (isnumberic(day)==1) {
                dataDo.setDay("0"+day);
            } else {
                dataDo.setDay(params.get("day").toString());
            }
            if (isnumberic(hour)==1) {
                dataDo.setHour("0"+hour);
            } else {
                dataDo.setHour(params.get("hour").toString());
            }
            if (isnumberic(minute)==1) {
                dataDo.setMinute("0"+minute);
            } else {
                dataDo.setMinute(params.get("minute").toString());
            }
            dataDo.setTime(params.get("year").toString() + "-"
                            + dataDo.getMonth() + "-"
                            + dataDo.getDay() +" "
                            + dataDo.getHour() + ":"
                            + dataDo.getMinute());
            dataDo.setLngDegree(params.get("lng_degree").toString());
            dataDo.setLngMinute(params.get("lng_minute").toString());
            dataDo.setLngSecond(params.get("lng_second").toString());
            dataDo.setLongitude(params.get("lng_degree").toString() + "°"
                                + params.get("lng_minute").toString() + "′"
                                + params.get("lng_second").toString() + "″");
            dataDo.setLatDegree(params.get("lat_degree").toString());
            dataDo.setLatMinute(params.get("lat_minute").toString());
            dataDo.setLatSecond(params.get("lat_second").toString());
            dataDo.setLatitude(params.get("lat_degree").toString() + "°"
                                + params.get("lat_minute").toString() + "′"
                                + params.get("lat_second").toString() + "″");
            dataDo.setDelFlag(0);
            testDataService.save(dataDo);
            return R.ok();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("上传失败");
        }
    }

    public static int isnumberic(String str){
        int count=1;
        for(int i=0;i<str.length();i++)
        {
            if(Character.isDigit(str.charAt(i))){   //判断字符是否为数字
                count++;
            }
        }
        return count;
    }

    /**
     * 历史数据
     *
     * deviceId:设备ID
     */
    @ResponseBody
    @PostMapping("/historyDataList")
    public R historyDataList(@RequestBody Map<String, Object> paramMap) {
        if (!paramMap.containsKey("device") || StringUtils.isBlank(paramMap.get("device").toString())

        ) {
            return R.error("缺少参数");
        }
        try {
            PageInfo<TestDataDo> list = testDataService.historyDataList(paramMap);
            return R.ok().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("获取失败");
        }
    }

    private Logger logger = LoggerFactory.getLogger(getClass());

    @RequestMapping({"/record"})
    public JSONObject record(String msg) {
        this.logger.info("收到设备上信息:{}", msg);
        JSONObject data = new JSONObject();
        // 设备编码
        data.put("device",msg.substring(10, 22));
        int length = Integer.parseInt(msg.substring(22, 24), 16);
        data.put("total", Integer.valueOf(length));
        List<JSONObject> list = new ArrayList<>();
        for (int i = 0; i < length; i++) {
            JSONObject param = new JSONObject();
            int num = 36 * i;
            // a参数
            String a = msg.substring(24 + num, 26 + num);
            if ("01".equals(a)) {
                a = "溶解氧(高)";
            } else if ("02".equals(a)) {
                a = "溶解氧(中)";
            } else if ("03".equals(a)) {
                a = "溶解氧(低)";
            } else if ("04".equals(a)) {
                a = "氨氮";
            } else if ("05".equals(a)) {
                a = "高亚硝酸盐氮";
            } else if ("06".equals(a)) {
                a = "低亚硝酸盐氮";
            } else if ("07".equals(a)) {
                a = "硝酸盐氮";
            } else if ("08".equals(a)) {
                a = "磷酸盐";
            } else if ("09".equals(a)) {
                a = "硫化物（高）";
            } else if ("0a".equals(a) || "0A".equals(a)) {
                a = "硫化物（低）";
            } else if ("0b".equals(a) || "0B".equals(a)) {
                a = "氰化物（高）";
            } else if ("0c".equals(a) || "0C".equals(a)) {
                a = "氰化物（低）";
            } else if ("0d".equals(a) || "0D".equals(a)) {
                a = "氟化物";
            } else if ("0e".equals(a) || "0E".equals(a)) {
                a = "氯化物（高）";
            } else if ("0f".equals(a) || "0F".equals(a)) {
                a = "氯化物（中）";
            } else if ("10".equals(a)) {
                a = "氯化物（低）";
            } else if ("11".equals(a)) {
                a = "硫酸盐";
            } else if ("12".equals(a)) {
                a = "碳酸盐";
            } else if ("13".equals(a)) {
                a = "重碳酸盐";
            } else if ("14".equals(a)) {
                a = "二氧化碳";
            } else if ("15".equals(a)) {
                a = "镉";
            } else if ("16".equals(a)) {
                a = "镍";
            } else if ("17".equals(a)) {
                a = "铅（高）";
//                param.put("yc", 1);
            } else if ("18".equals(a)) {
                a = "二价汞（高）";
            } else if ("19".equals(a)) {
                a = "二价汞（低）";
            } else if ("1a".equals(a) || "1A".equals(a)) {
                a = "六价铬";
            } else if ("1b".equals(a) || "1B".equals(a)) {
                a = "二价铜";
            } else if ("1c".equals(a) || "1C".equals(a)) {
                a = "锰";
            } else if ("1d".equals(a) || "1D".equals(a)) {
                a = "砷化物";
            } else if ("1e".equals(a) || "1E".equals(a)) {
                a = "低锌";
            } else if ("1f".equals(a) || "1F".equals(a)) {
                a = "高锌";
            } else if ("20".equals(a)) {
                a = "铝";
            } else if ("21".equals(a)) {
                a = "高镉";
            } else if ("22".equals(a)) {
                a = "总铁";
            } else if ("23".equals(a)) {
                a = "亚铁";
            } else if ("24".equals(a)) {
                a = "钙";
            } else if ("25".equals(a)) {
                a = "镁";
            } else if ("26".equals(a)) {
                a = "总硬度（高）";
            } else if ("27".equals(a)) {
                a = "总硬度(中)";
            } else if ("28".equals(a)) {
                a = "总硬度（低）";
            } else if ("29".equals(a)) {
                a = "高余氯";
            } else if ("2a".equals(a) || "2A".equals(a)) {
                a = "低余氯";
            } else if ("2b".equals(a) || "2B".equals(a)) {
                a = "二氧化氯";
            } else if ("2c".equals(a) || "2C".equals(a)) {
                a = "有效氯";
            } else if ("2d".equals(a) || "2D".equals(a)) {
                a = "PH-Ⅰ";
            } else if ("2e".equals(a) || "2E".equals(a)) {
                a = "PH-Ⅱ";
            } else if ("2f".equals(a) || "2F".equals(a)) {
                a = "PH-Ⅲ";
            } else if ("30".equals(a)) {
                a = "PH-Ⅳ";
            } else if ("31".equals(a)) {
                a = "色度";
            } else if ("32".equals(a)) {
                a = "硫酸";
            } else if ("33".equals(a)) {
                a = "盐酸";
            } else if ("34".equals(a)) {
                a = "硝酸";
            } else if ("35".equals(a)) {
                a = "苯胺";
            } else if ("36".equals(a)) {
                a = "水合肼";
            } else if ("37".equals(a)) {
                a = "挥发酚";
            } else if ("38".equals(a)) {
                a = "甲醛";
            } else if ("39".equals(a)) {
                a = "COD(高)";
            } else if ("3a".equals(a) || "3A".equals(a)) {
                a = "COD(中)";
            } else if ("3b".equals(a) || "3B".equals(a)) {
                a = "COD(低)";
            }
            param.put("name", a);

            // b整数位
            Integer b = Integer.valueOf(Integer.parseInt(msg.substring(26 + num, 30 + num), 16));
            // c小数位
            Integer c = Integer.valueOf(Integer.parseInt(msg.substring(30 + num, 34 + num), 16));

            // unit单位代码
            String unit = msg.substring(36 + num, 38 + num);
            if ("00".equals(unit)) {
                unit = "";
            } else if ("01".equals(unit)) {
                unit = "mg/L";
            } else if ("02".equals(unit)) {
                unit = "mol/L";
            } else if ("03".equals(unit)) {
                unit = "mmol/L";
            } else if ("04".equals(unit)) {
                unit = "ug/L";
            }

            // accuracy精度代码
            String accuracy = msg.substring(34 + num, 36 + num);
            if ("00".equals(accuracy)) {
                param.put("value", b + " " + unit);// 无小数
            } else if ("01".equals(accuracy)) {
                BigDecimal integerPlace1 = new BigDecimal(b);// 整数位
                BigDecimal decimalPlace1 = new BigDecimal(c);// 小数位
                BigDecimal divide1 = decimalPlace1.divide(new BigDecimal(100000));
                BigDecimal add1 = integerPlace1.add(divide1).setScale(1,BigDecimal.ROUND_HALF_UP);// 相加
                param.put("value", add1 + " " + unit);// 小数点后保留1位
            } else if ("02".equals(accuracy)) {
                BigDecimal integerPlace2 = new BigDecimal(b);// 整数位
                BigDecimal decimalPlace2 = new BigDecimal(c);// 小数位
                BigDecimal divide2 = decimalPlace2.divide(new BigDecimal(100000));
                BigDecimal add2 = integerPlace2.add(divide2).setScale(2,BigDecimal.ROUND_HALF_UP);// 相加
                param.put("value", add2 + " " + unit);// 小数点后保留2位
            } else if ("03".equals(accuracy)) {
                BigDecimal integerPlace3 = new BigDecimal(b);// 整数位
                BigDecimal decimalPlace3 = new BigDecimal(c);// 小数位
                BigDecimal divide3 = decimalPlace3.divide(new BigDecimal(100000));
                BigDecimal add3 = integerPlace3.add(divide3).setScale(3,BigDecimal.ROUND_HALF_UP);// 相加
                param.put("value", add3 + " " + unit);// 小数点后保留3位
            }

            // d年
            Integer d = Integer.valueOf(Integer.parseInt(msg.substring(38 + num, 40 + num), 16));
            param.put("year","20" + d);
            // e月
            Integer e = Integer.valueOf(Integer.parseInt(msg.substring(40 + num, 42 + num), 16));
            if ((e + "").length() == 1) {
                param.put("month","0" + e);
            } else {
                param.put("month", e);
            }
            // f日
            Integer f = Integer.valueOf(Integer.parseInt(msg.substring(42 + num, 44 + num), 16));
            if ((f+"").length() == 1) {
                param.put("day","0" + f);
            } else {
                param.put("day", f);
            }
            // g时
            Integer g = Integer.valueOf(Integer.parseInt(msg.substring(44 + num, 46 + num), 16));
            if ((g+"").length() == 1) {
                param.put("hour","0" + g);
            } else {
                param.put("hour", g);
            }
            // h分
            Integer h = Integer.valueOf(Integer.parseInt(msg.substring(46 + num, 48 + num), 16));
            if ((h + "").length() == 1) {
                param.put("minute","0" + h);
            } else {
                param.put("minute", h);
            }
            // j经度-度
            Integer j = Integer.valueOf(Integer.parseInt(msg.substring(48 + num, 50 + num), 16));
            if ((j + "").length() == 1) {
                param.put("lngDegree","0" + j);
            } else {
                param.put("lngDegree", j);
            }
            // k经度-分
            Integer k = Integer.valueOf(Integer.parseInt(msg.substring(50 + num, 52 + num), 16));
            if ((k +"").length() == 1) {
                param.put("lngMinute","0" + k);
            } else {
                param.put("lngMinute", k);
            }
            // l经度-秒
            Integer l = Integer.valueOf(Integer.parseInt(msg.substring(52 + num, 54 + num), 16));
            if ((l + "").length() == 1) {
                param.put("lngSecond","0" + l);
            } else {
                param.put("lngSecond", l);
            }
            // m纬度-度
            Integer m = Integer.valueOf(Integer.parseInt(msg.substring(54 + num, 56 + num), 16));
            if ((m + "").length() == 1) {
                param.put("latDegree","0" + m);
            } else {
                param.put("latDegree", m);
            }
            // n纬度-分
            Integer n = Integer.valueOf(Integer.parseInt(msg.substring(56 + num, 58 + num), 16));
            if ((n + "").length() == 1) {
                param.put("latMinute","0" + n);
            } else {
                param.put("latMinute", n);
            }
            // o纬度-秒
            Integer o = Integer.valueOf(Integer.parseInt(msg.substring(58 + num, 60 + num), 16));
            if ((o + "").length() == 1) {
                param.put("latSecond","0" + o);
            } else {
                param.put("latSecond", o);
            }
            list.add(param);
        }
        data.put("param", list);
//        this.jdbcTemplate.update("insert into L_history(device_no,content,msg,create_time)value(?,?,?,now())", new Object[] { data.get("device"), msg, data.toJSONString() });
        return data;
    }

//    @ResponseBody
//    @RequestMapping({"/list"})
//    public Object list(String device) {
//        String sql = "select * from L_history where 1=1 ";
//        if (device != null && device != "") {
//            sql = sql + "and device_no = ? order by id desc ";
//            return this.jdbcTemplate.queryForList(sql, new Object[] { device });
//        }
//        return this.jdbcTemplate.queryForList(sql + " order by id desc ");
//    }

}
